package com.aaa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CrosConfig {
    @Bean //方法上面
    // @Component 类上面
    public CorsFilter corsFilter(){
        // 跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许的域名
        // 谁可以访问后端的代码
        corsConfiguration.addAllowedOrigin("http://localhost:8080");// * 代表所有  http://localhost:8080
        // 允许的请求头
        corsConfiguration.addAllowedHeader("*");//
        // 请求方式
        corsConfiguration.addAllowedMethod("*");// get  post put delete
         corsConfiguration.setAllowCredentials(true);
        // 允许携带凭证
        corsConfiguration.addAllowedOriginPattern("*");//

        // 基于请求路径url的跨域源配置
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        // 所有的路径   都能跨域
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
